import os
import time
import threading
from queue import Queue
from .mysql_api import JetMySQL
from .download_img import downloadImage
from .getConfig import getConfig, logger

parent_save_path = getConfig().get('Image', 'save_path')
thread_size = getConfig().getint('Image', 'thread_size')
urls_pool = Queue()


def __get_image_info_from_db():
    mysql = JetMySQL()
    sql_cmd = "select companyName, category, productUrl, productImageUrl, productImageName \
               from {table} \
               where productImageStatus='no'".format(table="productList")
    sum_num = 0
    while True:
        query_result = mysql.executor(sql_cmd)
        new_num = len(query_result)
        sum_num += new_num
        logger.info("New items: %s, Total: %s" % (new_num, sum_num))
        for info in query_result:
            urls_pool.put(info)
        urls_pool.join()

        if not new_num:
            time.sleep(5)


def __update_image_status(mysql_object, productUrl, downloadStatus):
    update_cmd = "update {table} \
                  set productImageStatus='{productImageStatus}' \
                  where productUrl='{productUrl}'\
                  ".format(table="productList",
                           productImageStatus=downloadStatus,
                           productUrl=productUrl)
    mysql_object.executor(update_cmd)
    mysql_object.conn.commit()


def __download_task(num):
    update_mysql = JetMySQL()
    sum = 0
    while True:
        image_info = urls_pool.get()
        sum += 1
        # logger.info("[Thread_%s]: downloading...%s" % (num, sum))

        img_save_path = downloadImage.imgs_save_path(
            image_info["companyName"], image_info["category"])
        img_name = downloadImage.format_img_name(
            name=image_info["productImageName"])

        download_status = downloadImage.download(image_info["productImageUrl"],
                                                 img_name,
                                                 img_save_path)

        __update_image_status(
            update_mysql, image_info["productUrl"], download_status)
        urls_pool.task_done()


def download_main():
    get_images_thread = threading.Thread(
        target=__get_image_info_from_db, args=())
    get_images_thread.start()

    for num in range(thread_size):
        t = threading.Thread(target=__download_task, args=(num,))
        t.start()


if __name__ == "__main__":
    download_main()
